import React from "react";
import { Page, Input } from "zmp-ui";
import { useI18n } from "../i18n";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { useSetRecoilState } from "recoil";
import { selectedCountryCodeState } from "../state";
import { getPhoneCodesWithLocalizedNames, PhoneCode } from "../utils/phone-codes";

interface CountryItem extends PhoneCode {
  displayName: string;
}

const CountryCode: React.FunctionComponent = () => {
  const { t, locale } = useI18n();
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const setSelectedCountryCode = useSetRecoilState(selectedCountryCodeState);
  
  const [searchCode, setSearchCode] = React.useState("");
  
  // 根据当前语言获取本地化的国家列表
  const countryList = React.useMemo(() => {
    return getPhoneCodesWithLocalizedNames(locale);
  }, [locale]);

  // 过滤国家列表
  const filteredList = React.useMemo(() => {
    if (!searchCode) return countryList;
    
    const searchTerm = searchCode.toLowerCase();
    const reg = new RegExp(searchTerm, "ig");
    
    return countryList.filter((item) => {
      return String(item.displayName + item.code + item.name_zh + item.name_vi).match(reg);
    });
  }, [searchCode, countryList]);

  // 选择国家代码
  const selectCode = (code: string) => {
    // 保存选中的国家代码到状态管理
    setSelectedCountryCode(code);
    // 返回到上一页
    navigate(-1);
  };

  // 返回
  const goBack = () => {
    // 返回到上一页
    navigate(-1);
  };


  return (
    <Page className="page" style={{ background: '#fff' }}>
      <div style={{
        width: '100%',
        minHeight: '100vh',
        position: 'fixed',
        left: 0,
        top: 0,
        zIndex: 4000,
        background: '#ffffff'
      }}>
        {/* 顶部搜索栏 */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          height: 44,
          position: 'fixed',
          zIndex: 9,
          width: 'calc(100% - 14px)',
          background: '#ffffff',
          padding: '0 7px'
        }}>
          <img
            src="/src/assets/img/login/nav_ic_back_dark@2x.png"
            alt=""
            style={{ width: 44, marginRight: 10, cursor: 'pointer' }}
            onClick={goBack}
          />
          <Input
            type="text"
            placeholder={t('login.search')}
            value={searchCode}
            onChange={(e) => setSearchCode(String(e.target.value).replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ''))}
            style={{
              height: 32,
              background: '#f0f0f2',
              borderRadius: 16,
              fontSize: 12,
              color: '#39304d',
              border: 'none',
              paddingLeft: 32,
              flex: 1
            }}
          />
        </div>

        {/* 占位空间 */}
        <div style={{ height: 44 }}></div>

        {/* 国家列表 */}
        <div style={{ paddingTop: 0 }}>
          {filteredList.length > 0 ? (
            filteredList.map((item, index) => (
              <div
                key={index}
                onClick={() => selectCode(item.code)}
                style={{
                  width: 'calc(100% - 56px)',
                  marginLeft: 28,
                  height: 52,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  borderBottom: '1px solid #f6f6f6',
                  fontSize: 14,
                  lineHeight: '16px',
                  fontWeight: 500,
                  cursor: 'pointer'
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <span style={{
                    fontSize: 20,
                    marginRight: 16
                  }}>
                    {item.flag}
                  </span>
                  <span style={{ textAlign: 'left', color: '#646B80' }}>
                    {item.displayName}
                  </span>
                </div>
                <span style={{ textAlign: 'right', color: '#39304d' }}>
                  +{item.code}
                </span>
              </div>
            ))
          ) : (
            <div style={{
              width: 'calc(100% - 56px)',
              marginLeft: 28,
              textAlign: 'center',
              color: '#7b7e92',
              fontSize: 16,
              fontWeight: 500,
              marginTop: 28
            }}>
              {t('error.empty')} ~
            </div>
          )}
        </div>
      </div>
    </Page>
  );
};

export default CountryCode;
